package com.bing.controller.blog;

import com.bing.entity.CStatus;
import com.bing.entity.PStatus;
import com.bing.entity.Post;
import com.bing.services.BlogService;
import com.bing.services.EnvService;
import com.bing.utils.UtilFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kaibb on 15-12-5.
 */

@Controller
@RequestMapping(HelloBlog.BLOG)
public class HelloBlog {
    public static final String BLOG = "blog";

    private static final Logger LOGGER = LoggerFactory.getLogger(HelloBlog.class);

    @Autowired
    private BlogService blogService;

    @Autowired
    private EnvService envService;

    @RequestMapping("view-{pageNo:\\d+}")
    public String index(@PathVariable(value = "pageNo") int pageNo, Model model) {
        List<Post> posts = blogService.getPostsPaged(pageNo, envService.getPageSize());
        final double postNum = Math.ceil(blogService.getPostNum());
        LOGGER.info("view blog at {}, total:{}", pageNo, postNum);
        model.addAttribute(posts);
        model.addAttribute("pageNo", pageNo);
        model.addAttribute("pageSize", Math.ceil(postNum / envService.getPageSize()));
        return BLOG + "/index";
    }

    @RequestMapping("hot")
    public String hot(Model model) {
        List<Post> posts = blogService.getHotPosts(envService.getHotSize());
        LOGGER.info("view hot blog!");
        model.addAttribute(posts);
        return BLOG + "/hot";
    }


    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String create(Post post, Model model) {
        LOGGER.info("create blog post:{}", post);
        model.addAttribute(post);
        model.addAttribute(CStatus.values());
        model.addAttribute(PStatus.values());
        return BLOG + "/create";
    }

    @RequestMapping(value = "edit/{id:\\d+}", method = RequestMethod.GET)
    public String update(@PathVariable Long id, Model model) {
        LOGGER.info("edit blog post:{}", id);
        Post post = blogService.getPost(id);
        return create(post, model);
    }

    @RequestMapping(value = "delete/{id:\\d+}", method = RequestMethod.GET)
    @ResponseBody
    public String delete(@PathVariable Long id, Model model) {
        LOGGER.info("删除文章:{}", id);
        blogService.deletePost(id);
        return "succ";
    }


    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String save(@Validated Post post, BindingResult result, Model model) {
        LOGGER.info("保存文章:{}", post);
        if (result.hasErrors()) {
            LOGGER.info("文章非法:{}", result.getAllErrors());
        } else {
            post.setExcerpt(UtilFactory.getExcerpt(post.getExcerpt()));
            blogService.createPost(post);
        }
        return create(post, model);
    }

    @RequestMapping(value = "{id}", method = RequestMethod.GET, consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public Post getBlogById(@PathVariable("id") long id) {
        Post post = blogService.getPost(id);
        post.setContent(UtilFactory.getMD(post.getContent()));
        return post;
    }


    @RequestMapping(value = "id/{id:[\\d]+}", method = RequestMethod.GET)
    public String viewById(Model model, @PathVariable("id") long id) {
        LOGGER.info("view Blog:{}", id);
        Post post = blogService.getPost(id);
        post.setBrowses(post.getBrowses() + 1);
        blogService.updatePost(post);
        post.setContent(UtilFactory.getMD(post.getContent()));
        model.addAttribute(post);
        return "blog/view";
    }

    @RequestMapping(value = "title/{title:.+}", method = RequestMethod.GET)
    public String viewByName(Model model, @PathVariable("title") String title) {
        LOGGER.info("view Blog by Title:{}", title);
        Post post = blogService.getPostByTitle(title);
        post.setBrowses(post.getBrowses() + 1);
        blogService.updatePost(post);
        post.setContent(UtilFactory.getMD(post.getContent()));
        model.addAttribute("prePost", blogService.getPre(post.getId()));
        model.addAttribute("nextPost", blogService.getNext(post.getId()));
       model.addAttribute("tagPost", blogService.getPostsPagedByTag(1, envService.getInt("tagSize"), new ArrayList<>(post.getTags())));
        model.addAttribute(post);
        return "blog/view";
    }

}
